package cool.tianyou.blue.bird.module.synchronize.websocket;

import cool.tianyou.blue.bird.module.auth.service.UserService;
import cool.tianyou.blue.bird.module.synchronize.service.WebSocketService;
import java.io.IOException;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

/**
 * @author user
 */
@ServerEndpoint(value = "/webSocket/{token}/{deviceId}", configurator = CustomSpringConfigurator.class)
@Component
@RequiredArgsConstructor
public class WebSocketServer {


  public final UserService userService;
  public final WebSocketService webSocketService;



  @OnOpen
  public void onOpen(Session session,
      @PathParam(value = "token") String token,
      @PathParam(value = "deviceId") Integer deviceId) {
    webSocketService.onOpen(session, token, deviceId);

  }

  @OnClose
  public void onClose(Session session) {
    System.out.println(session);
//    webSocketService.removeSession(session);
  }

  @OnMessage
  public void onMessage(Session session, String message) throws IOException {
    webSocketService.onMessage(session, message);
  }

  /**
   * socket 错误时调用
   */
  @OnError
  public void onError(Session session, Throwable throwable) {
    throwable.printStackTrace();
    //TODO removeSession
//    webSocketService.removeSession(session);
    ;
  }

}
